package com.concurrent.concurrentdemo.lock;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.CountDownLatch;

public class UnsafeDemo {

    //获取Unsafe实例
    static final Unsafe unsafe;
    //记录state在类TestUsafe中的偏移值
    static final long stateOffset;
    //变量
    public volatile long result = 0;

    static {
        try {
            //获取成员变量
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            //设置为可访问
            field.setAccessible(true);
            //是静态字段,用null来获取Unsafe实例
            unsafe = (Unsafe) field.get(null);
            //获取state变量在类中的偏移值
            stateOffset = unsafe.objectFieldOffset(UnsafeDemo.class.getDeclaredField("result"));
        } catch (Exception e) {
            System.out.println(e.getLocalizedMessage());
            throw new Error(e);
        }
    }

    public static void plus(UnsafeDemo unsafeDemo) {
        while (true) {
            long oldValue = unsafe.getLongVolatile(unsafeDemo, stateOffset);
            if (unsafe.compareAndSwapLong(unsafeDemo, stateOffset, oldValue, oldValue + 1)) break;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        UnsafeDemo unsafeDemo = new UnsafeDemo();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 100000; j++) {
                    UnsafeDemo.plus(unsafeDemo);
                }
                countDownLatch.countDown();
            }).start();
        }
        countDownLatch.await();
        System.out.println(unsafeDemo.result);
    }

}
